﻿using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using System.Collections.Generic;
using System.Xml;

/// <summary>
/// 淘宝宝贝相关
/// </summary>
public class TB_BaoBei
{
    public TB_BaoBei()
    {        
    }
    /// <summary>
    /// 下载淘宝宝贝列表及详细数据
    /// </summary>  
    /// <returns>返回下载总条数</returns>
    public int DownTBBaobei(string username,string password,string appkey,string certcode,string sessionId)
    {
        string[,] param = new string[,] { { "nick", username }, { "sip_apiname", "taobao.items.onsale.get" }, 
                    { "fields", "approve_status,iid,title,nick,type,cid,pic_path,num,props,valid_thru, list_time,price,has_discount,has_invoice,"+
                        "has_warranty,has_showcase, modified,delist_time,postage_id,seller_cids " }, {"page_size","1024"},
                    { "v", "1.0" }, { "sip_timestamp", System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") }, { "sip_format", "xml" },{"sip_appkey",appkey}};
        BS2.BSTaobaoAPI.TaobaoAPI.setAPPID(appkey);
        BS2.BSTaobaoAPI.TaobaoAPI.setCERTCODE(certcode);
        BS2.BSTaobaoAPI.TaobaoAPI.setLoginPro(username, password);
        BS2.BSTaobaoAPI.TaobaoAPI.setSessionID(sessionId);
        XmlDocument xml = BS2.BSTaobaoAPI.TaobaoAPI.getXmlFromTaobao(param, username, password, certcode);
        if (xml == null || xml.OuterXml.Contains("error_rsp"))
            return 0;
        int rowCount = Convert.ToInt32(xml.SelectNodes("rsp/totalResults").Item(0).InnerText);
        string[] idds = new string[rowCount];
        for (int i = 0; i < idds.Length; i++)
            idds[i] = xml.SelectNodes("rsp/item").Item(i).InnerText; 
        //依次获取每个宝贝的详细数据，然后导入数据库       
        int myCount = 0;
        for (int i = 0; i < idds.Length; i++)
        {
            DownTBBaobei(username, password, appkey, certcode, sessionId, idds[i]);
            myCount++;
        }
        return myCount;
    }
    /// <summary>
    /// 按照param的条件，下载宝贝列表，并存入数据库
    /// </summary> 
    public int DownTBBaoBei(string username, string password, string appkey, string certcode, string sessionId, string[,] param)
    {
        int count = 0;
        int pageno = 1;
        while (true)
        {
            int ret = DownTBBaoBei(username, password, appkey, certcode, sessionId, param, pageno);
            pageno++;
            count += ret;
            if (ret == 0 || ret != 100)
                break;
        }
        return count;
    }
    int DownTBBaoBei(string username, string password, string appkey, string certcode, string sessionId, string [,] param,int pageno)
    {
        param[0, 1] = "100";
        param[1, 1] = pageno.ToString();
        BS2.BSTaobaoAPI.TaobaoAPI.setAPPID(appkey);
        BS2.BSTaobaoAPI.TaobaoAPI.setCERTCODE(certcode);
        BS2.BSTaobaoAPI.TaobaoAPI.setLoginPro(username, password);
        BS2.BSTaobaoAPI.TaobaoAPI.setSessionID(sessionId);
        XmlDocument xml = BS2.BSTaobaoAPI.TaobaoAPI.getXmlFromTaobao(param, username, password, certcode);
        if (xml == null || xml.OuterXml.Contains("error_rsp"))
            return 0;
        return SaveBBbyXml(xml, username);               
    }
    int SaveBBbyXml(XmlDocument xml,string username)
    {
        DataSet ds = new DataSet();
        ds.ReadXml(new XmlNodeReader(xml));
        if (ds != null && ds.Tables.Count > 0)
        {
            DataTable dt = ds.Tables["item"];
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                //判断宝贝是否存在，如果存在，则不下载
                if (new TBCommon().IsBaobeiExist(dt.Rows[i]["iid"].ToString(),GetShopMid(username)))
                    continue;
                Model.TaoBao.TB_BAOBEI item = new Model.TaoBao.TB_BAOBEI();
                item.PID = GetShopMid(username); //淘宝商店MID
                item.BBMC = dt.Rows[i]["title"].ToString();
                //item.BBMS = myItem._desc;
                item.BBSL = Convert.ToInt32(dt.Rows[i]["num"]);
                item.BX = dt.Rows[i]["has_warranty"].ToString() == "true" ? 1 : 0;
                item.CC = dt.Rows[i]["has_showcase"].ToString() == "true" ? 1 : 0;
                //item.CF = myItem._auto_repost == "true" ? 1 : 0;
                item.CSFS = dt.Rows[i]["type"].ToString();
                //item.DM_ID = Convert.ToInt32(myItem._seller_cids);
                //item.DQ_ID = 0;//所在地编号，暂缓
                //item.DQDM = myItem._location;// 所在地代码
                //item.DQMC = myItem._location_state + "," + myItem._location_city;
                //item.EMS = Convert.ToDecimal(myItem._ems_fee);
                item.FBSJ = Convert.ToDateTime(dt.Rows[i]["list_time"]);
                item.FP = dt.Rows[i]["has_invoice"].ToString() == "true" ? 1 : 0;
                item.HYDZ = dt.Rows[i]["has_discount"].ToString() == "true" ? 1 : 0;
                //item.JJ = (int)Convert.ToDouble(myItem._increment);
                //item.KD = Convert.ToDecimal(myItem._express_fee);
                item.LMDM = dt.Rows[i]["cid"].ToString();
                item.LMMC = new TBCommon().GetTBLeiMuNamebyCode(dt.Rows[i]["cid"].ToString());
                //item.PY = Convert.ToDecimal(myItem._post_fee);
                item.TN_ID = 0;
                //item.XJCD = myItem._stuff_status;
                //item.YFCD = myItem._freight_payer;
                item.YKJ = Convert.ToDecimal(dt.Rows[i]["price"]);
                item.YXQ = dt.Rows[i]["valid_thru"].ToString();
                item.field1 = dt.Rows[i]["iid"].ToString();
                
                int MID = new BLL.TaoBao.TB_BAOBEI().Add(item);
                //宝贝属性,tb_baobeiProps
                //props:20086:21040;20088:21073;20089:21108;20000:81443   
                 InsertIntoBaoBeiProps(dt.Rows[i]["props"].ToString(), MID);               
            }
            return dt.Rows.Count;
        }
        return 0;
    }
    public void DownTBBaobei(string username, string password, string appkey, string certcode, string sessionId, string iid)
    {
        string fields = "title,cid,seller_cids,stuff_status,location,type,price,num,increment,valid_thru,freight_payer,post_fee,express_fee,ems_fee,has_invoice,has_warranty," +
                "auto_repost,approve_status,has_showcase,has_discount,list_time,desc,product_id,props";
        string [,] param = new string[,] {{"iid", iid }, {"nick",username},{ "sip_apiname", "taobao.item.get" }, { "fields", fields }, 
                    { "v", "1.0" }, { "sip_timestamp", System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") }, { "sip_format", "xml" },{"sip_appkey",appkey}};
        XmlDocument xml = null;
        xml = BS2.BSTaobaoAPI.TaobaoAPI.getXmlFromTaobao(param, username, password, certcode);
        if (xml == null || xml.OuterXml.Contains("error_rsp"))
            return;
        BS2.BSTaobaoAPI.BSTaobaoItem myItem = GetItemFromXml(xml);
        InsertIntoBaoBeiProps(myItem._props, 12);           
       
    }
    //插入宝贝属性
    void InsertIntoBaoBeiProps(string props,int Mid)
    {
        if (props == null || props.Length == 0)
            return;
        props = props + ";";
        int len = props.Length - props.Replace(";", "").Length;
        string[] propItems = new string[len];
        for (int i = 0; i < len; i++)
            propItems[i] = props.Split(';')[i];
        //20000:81443
        List<Model.TaoBao.TB_BaobeiProps> bbList = new List<Model.TaoBao.TB_BaobeiProps>();      
        for (int i = 0; i < len; i++)
        {            
            Model.TaoBao.TB_BaobeiProps p = new Model.TaoBao.TB_BaobeiProps();           
            p.PID = Mid;
            p.SX_ID = propItems[i].Split(':')[0];
            int tb_id = Convert.ToInt32(propItems[i].Split(':')[1]);
            Model.TaoBao.TB_SXLINK sx = GetTB_SXLinkbyTb_Id(tb_id);
            if (sx != null)
            {
                p.SXMC = sx.LMSX;
                p.NR_ID = tb_id.ToString();
                p.NRMC = sx.LSNR;
            }
            bbList.Add(p);
        }
        new BLL.TaoBao.TB_BaobeiProps().Add(bbList);
    }
    Model.TaoBao.TB_SXLINK GetTB_SXLinkbyTb_Id(int tb_id)
    {
        Model.TaoBao.TB_SXLINK link = new Model.TaoBao.TB_SXLINK();
        string sql = "select mid,lmsx,lsnr from tb_sxlink where tb_id=" + tb_id;
        DataSet ds = DBUtility.SqlHelper.Query(DBUtility.SqlHelper.LocalSqlServer, sql);
        if (ds == null || ds.Tables.Count == 0 || ds.Tables[0].Rows.Count == 0)
            return null;
        link.MID = Convert.ToInt32(ds.Tables[0].Rows[0][0]);
        link.LMSX = ds.Tables[0].Rows[0][1].ToString();
        link.LSNR = ds.Tables[0].Rows[0][2].ToString();
        return link;
    }
    /// <summary>
    /// 获取商店mid
    /// </summary>
    int GetShopMid(string name)
    {
        return new TBCommon().GetShopIdByZH(name);        
    }
    BS2.BSTaobaoAPI.BSTaobaoItem GetItemFromXml(XmlDocument xml)
    {
        BS2.BSTaobaoAPI.BSTaobaoItem t = new BS2.BSTaobaoAPI.BSTaobaoItem();
        foreach (XmlNode node in xml.SelectNodes("/rsp/item"))
        {
            if (node.SelectNodes("iid").Item(0) != null)
            {
                t._iid = node.SelectNodes("iid").Item(0).InnerText;
            }
            if (node.SelectNodes("title").Item(0) != null)
            {
                t._title = node.SelectNodes("title").Item(0).InnerText;
            }
            if (node.SelectNodes("nick").Item(0) != null)
            {
                t._nick = node.SelectNodes("nick").Item(0).InnerText;
            }
            if (node.SelectNodes("type").Item(0) != null)
            {
                t._type = node.SelectNodes("type").Item(0).InnerText;
            }
            if (node.SelectNodes("cid").Item(0) != null)
            {
                t._cid = node.SelectNodes("cid").Item(0).InnerText;
            }
            if (node.SelectNodes("seller_cids").Item(0) != null)
            {
                t._seller_cids = node.SelectNodes("seller_cids").Item(0).InnerText;
            }
            if (node.SelectNodes("props").Item(0) != null)
            {
                t._props = node.SelectNodes("props").Item(0).InnerText;
            }
            if (node.SelectNodes("desc").Item(0) != null)
            {
                t._desc = node.SelectNodes("desc").Item(0).InnerText;
            }
            if (node.SelectNodes("pic_path").Item(0) != null)
            {
                t._pic_path = node.SelectNodes("pic_path").Item(0).InnerText;
            }
            if (node.SelectNodes("num").Item(0) != null)
            {
                t._num = node.SelectNodes("num").Item(0).InnerText;
            }
            if (node.SelectNodes("valid_thru").Item(0) != null)
            {
                t._valid_thru = node.SelectNodes("valid_thru").Item(0).InnerText;
            }
            if (node.SelectNodes("list_time").Item(0) != null)
            {
                t._list_time = node.SelectNodes("list_time").Item(0).InnerText;
            }
            if (node.SelectNodes("delist_time").Item(0) != null)
            {
                t._delist_time = node.SelectNodes("delist_time").Item(0).InnerText;
            }
            if (node.SelectNodes("stuff_status").Item(0) != null)
            {
                t._stuff_status = node.SelectNodes("stuff_status").Item(0).InnerText;
            }
            if (node.SelectNodes("location").Item(0) != null)
            {
                t._location_state = node.SelectNodes("location/state").Item(0).InnerText;
                t._location_city = node.SelectNodes("location/city").Item(0).InnerText;
            }
            if (node.SelectNodes("price").Item(0) != null)
            {
                t._price = node.SelectNodes("price").Item(0).InnerText;
            }
            if (node.SelectNodes("post_fee").Item(0) != null)
            {
                t._post_fee = node.SelectNodes("post_fee").Item(0).InnerText;
            }
            if (node.SelectNodes("express_fee").Item(0) != null)
            {
                t._express_fee = node.SelectNodes("express_fee").Item(0).InnerText;
            }
            if (node.SelectNodes("ems_fee").Item(0) != null)
            {
                t._ems_fee = node.SelectNodes("ems_fee").Item(0).InnerText;
            }
            if (node.SelectNodes("has_discount").Item(0) != null)
            {
                t._has_discount = node.SelectNodes("has_discount").Item(0).InnerText;
            }
            if (node.SelectNodes("freight_payer").Item(0) != null)
            {
                t._freight_payer = node.SelectNodes("freight_payer").Item(0).InnerText;
            }
            if (node.SelectNodes("has_invoice").Item(0) != null)
            {
                t._has_invoice = node.SelectNodes("has_invoice").Item(0).InnerText;
            }
            if (node.SelectNodes("has_warranty").Item(0) != null)
            {
                t._has_warranty = node.SelectNodes("has_warranty").Item(0).InnerText;
            }
            if (node.SelectNodes("has_showcase").Item(0) != null)
            {
                t._has_showcase = node.SelectNodes("has_showcase").Item(0).InnerText;
            }
            if (node.SelectNodes("modified").Item(0) != null)
            {
                t._modified = node.SelectNodes("modified").Item(0).InnerText;
            }
            if (node.SelectNodes("increment").Item(0) != null)
            {
                t._increment = node.SelectNodes("increment").Item(0).InnerText;
            }
            if (node.SelectNodes("auto_repost").Item(0) != null)
            {
                t._auto_repost = node.SelectNodes("auto_repost").Item(0).InnerText;
            }
            if (node.SelectNodes("approve_status").Item(0) != null)
            {
                t._approve_status = node.SelectNodes("approve_status").Item(0).InnerText;
            }
            if (node.SelectNodes("postage_id").Item(0) != null)
            {
                t._postage_id = node.SelectNodes("postage_id").Item(0).InnerText;
            }
            if (node.SelectNodes("product_id").Item(0) != null)
            {
                t._product_id = node.SelectNodes("product_id").Item(0).InnerText;
            }
            if (node.SelectNodes("auction_point").Item(0) != null)
            {
                t._auction_point = node.SelectNodes("auction_point").Item(0).InnerText;
            }
            if (node.SelectNodes("property_alias").Item(0) != null)
            {
                t._property_alias = node.SelectNodes("property_alias").Item(0).InnerText;
            }
            break;
        }
        return t;
    }
}
